import { Appender } from '../interface/Appender'
import { LoggerLevel } from '../interface/LoggerLevel'

// noinspection JSUnusedGlobalSymbols
/**
 * BrowserIndexDbRecorder
 *
 * @author 冰凝
 * @date 2022/12/10 21:26
 */
export class BrowserIndexDbAppender implements Appender<any> {
    public config: any
    private db: IDBDatabase

    constructor(config: any) {
        this.config = config
        window.addEventListener('load', () => this.initDatabase())
    }

    public append(name: string, level: LoggerLevel, ...args: Array<any>): void {
    }

    private initDatabase(): void {
        const request: IDBOpenDBRequest = window.indexedDB.open('es-tool-log:BrowserIndexDbRecorder', 1)
        request.onerror = () => console.log('数据库无法打开')
        request.onsuccess = () => {
            console.log('数据库已成功打开')
            this.db = request.result
        }
        // 设置数据库表（如果尚未完成）
        request.onupgradeneeded = (e) => {
            // 获取对打开的数据库的引用
            // @ts-ignore
            const db = e.target?.result
            const objectStore: IDBObjectStore = db.createObjectStore('log', { keyPath: 'id', autoIncrement: true })
            objectStore.createIndex('log', 'log', { unique: false })
            console.log('数据库设置完成')
        }
    }

}
